const jwt = require('jsonwebtoken')
const {privateKey, currentUser} = require('../configs/auth')
const User = require('../models/user')

module.exports = async (req, res, next) => {
	try {
		const raw = req.headers.authorization.split(' ').pop();
		const { id } = jwt.verify(raw, privateKey)
		const user = await User.findById(id)
		if (!user) {
			throw Error('无效的用户')
		}
		req[currentUser] = user;
		next()
	} catch (err) {
		res.json({
			code: 401,
			message: 'token无效'
		})
	}
}